//
//  ZCLoginVC.m
//  zctx
//
//  Created by Yi luqi on 15/10/7.
//  Copyright © 2015年 sanliang. All rights reserved.
//

#import "ZCLoginVC.h"
#import "WXApi.h"
@interface ZCLoginVC (){
    UIButton *weChatButton;
    UIButton *codeButton;
}
@property (nonatomic,strong)UIView *bgtextView;
@property (nonatomic,strong)UIView *teleponeView;
@property (nonatomic,strong)UIView *codeView;
@property (nonatomic,strong)UITextField *teleponeField;
@property (nonatomic,strong)UITextField *codeField;
@property (nonatomic, assign) BOOL bIsNewOne;

@end

@implementation ZCLoginVC

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.view.shiftHeightAsDodgeViewForMLInputDodger = 50.0f;
    [self.view registerAsDodgeViewForMLInputDodger];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"用户登录";
    self.view.backgroundColor = RGB(242,242,242);
    
    [self initnavegation];
    [self initTextView];
    [self initConfirmButtonView];
    
    
    NSLog(@"判断微信是否安装 %d = ",[WXApi isWXAppInstalled]);
    if ([WXApi isWXAppInstalled]) {
        weChatButton.hidden = NO;
    }else{
        weChatButton.hidden = YES;
    }
    
}

#pragma mark 导航栏
-(void)initnavegation{
    
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 19, 36);
    [leftButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_leftNavBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = barButtonItem_leftNavBar;
}

-(void)backButtonPressed{
    ProgressDismiss;
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

-(void)initTextView{
    //手机号
    self.teleponeView = [UIView new];
    [self.view addSubview:self.teleponeView];
    self.teleponeView.backgroundColor = [UIColor whiteColor];
    [self.teleponeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.height.mas_equalTo(@50);
        make.top.equalTo(self.view).with.offset(64+40);
    }];
    
    UIView *teleView = [UIView new];
    [self.teleponeView addSubview:teleView];
    [teleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.teleponeView.mas_centerY);
        make.left.equalTo(self.view).with.offset(15);
        make.width.mas_equalTo(@25);
        make.height.mas_equalTo(@25);
    }];
    self.teleponeField = [UITextField new];
    [self.teleponeView addSubview:self.teleponeField];
    self.teleponeField.keyboardType = UIKeyboardTypeNumberPad;
    self.teleponeField.placeholder = @"请输入手机号";
    self.teleponeField.font = [UIFont systemFontOfSize:15];
    [self.teleponeField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.teleponeView.mas_centerY);
        make.right.equalTo(self.view).with.offset(-15);
        make.left.equalTo(teleView.right).with.offset(10);
        make.height.mas_equalTo(@25);
    }];
    
    //电话图片
    UIImageView *teleImageView = [UIImageView new];
    [teleView addSubview:teleImageView];
    [teleImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(teleView.mas_centerY);
        make.left.equalTo(teleView.left).with.offset(0);
        make.height.mas_equalTo(@18);
        make.width.mas_equalTo(@18);
    }];
    [teleImageView setImage:[UIImage imageNamed:@"login_telephone.png"]];
    
    UIImageView *telelineImageView = [UIImageView new];
    [teleView addSubview:telelineImageView];
    telelineImageView.image = [UIImage imageNamed:@"login_line.png"];
    [telelineImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.teleponeView.mas_centerY);
        make.right.equalTo(teleView.right).with.offset(0);
        make.width.mas_equalTo(@1.5);
        make.height.mas_equalTo(@25);
    }];
    
    //line
    UIView *lineView = [UIView new];
    lineView.backgroundColor = RGB(240, 238, 239);
    [self.view addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.teleponeView.bottom).with.offset(0);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.height.mas_equalTo(@1);
    }];
    
    //验证码
    self.codeView = [UIView new];
    [self.view addSubview:self.codeView];
    self.codeView.backgroundColor = [UIColor whiteColor];
    
    [self.codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.height.mas_equalTo(@50);
        make.top.equalTo(lineView.bottom).with.offset(0);
    }];
    
    UIView *infoView = [UIView new];
    [self.codeView addSubview:infoView];
    [infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.codeView.mas_centerY);
        make.left.equalTo(self.view).with.offset(15);
        make.width.mas_equalTo(@25);
        make.height.mas_equalTo(@25);
    }];
    
    self.codeField = [UITextField new];
    [self.codeView addSubview:self.codeField];
    self.codeField.placeholder = @"请输入验证码";
    self.codeField.keyboardType = UIKeyboardTypeNumberPad;
    self.codeField.font = [UIFont systemFontOfSize:15];
    [self.codeField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.codeView.mas_centerY);
        make.left.equalTo(infoView.right).with.offset(10);
        make.height.mas_equalTo(@25);
        make.width.mas_equalTo(@((SCREEN_WIDTH-30)/2));
    }];
    
    //验证码图片
    UIImageView *infoImageView = [UIImageView new];
    [infoView addSubview:infoImageView];
    [infoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.codeView.mas_centerY);
        make.left.equalTo(infoView.left).with.offset(0);
        make.height.mas_equalTo(@18);
        make.width.mas_equalTo(@18);
    }];
    [infoImageView setImage:[UIImage imageNamed:@"login_Information.png"]];
    
    UIImageView *infolineImageView = [UIImageView new];
    [infoView addSubview:infolineImageView];
    infolineImageView.image = [UIImage imageNamed:@"login_line.png"];
    [infolineImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.codeView.mas_centerY);
        make.right.equalTo(infoView.right).with.offset(0);
        make.width.mas_equalTo(@1.5);
        make.height.mas_equalTo(@25);
    }];
    
    //获取短信验证码按钮
    codeButton = [UIButton new];
    [self.codeView addSubview:codeButton];
    codeButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [codeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.codeView.mas_centerY);
        make.right.equalTo(self.codeView.right).with.offset(-15);
        make.left.equalTo(self.codeField.right).with.offset(5);
        make.height.mas_equalTo(@30);
    }];
    [codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [codeButton setBackgroundImage:[UIImage imageNamed:@"login_code_n"] forState:UIControlStateNormal];
    [codeButton setBackgroundImage:[UIImage imageNamed:@"login_code_h"] forState:UIControlStateHighlighted];
    [codeButton addTarget:self action:@selector(ClickCodeButton) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)initConfirmButtonView{
    
    //登录按钮
    UIButton *confirmButton = [UIButton new];
    [self.view addSubview:confirmButton];
    [confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.codeView.bottom).with.offset(30);
        make.right.equalTo(self.view).with.offset(-30);
        make.left.equalTo(self.view).with.offset(30);
        make.height.mas_equalTo(@35);
    }];
    [confirmButton addTarget:self action:@selector(ClickconfirmButton) forControlEvents:UIControlEventTouchUpInside];
    [confirmButton setBackgroundImage:[UIImage imageNamed:@"login_login_n"] forState:UIControlStateNormal];
    [confirmButton setBackgroundImage:[UIImage imageNamed:@"login_login_h"] forState:UIControlStateHighlighted];
    
    UILabel *otherLoginLable = [UILabel new];
    [self.view addSubview:otherLoginLable];
    [otherLoginLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(confirmButton.bottom).with.offset(40);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(120);
        make.height.mas_equalTo(@20);
    }];
    otherLoginLable.textAlignment = NSTextAlignmentCenter;
    otherLoginLable.font = [UIFont systemFontOfSize:13];
    otherLoginLable.textColor = [UIColor grayColor];
    otherLoginLable.text = @"使用第三方账号登录";
    
    UIView *leftView = [UIView new];
    [self.view addSubview:leftView];
    leftView.backgroundColor = [UIColor grayColor];
    [leftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(otherLoginLable.mas_centerY);
        make.right.equalTo(otherLoginLable.left).with.offset(0);
        make.left.equalTo(self.view).with.offset(0);
        make.height.mas_equalTo(@1);
    }];
    
    UIView *rightView = [UIView new];
    [self.view addSubview:rightView];
    rightView.backgroundColor = [UIColor grayColor];
    [rightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(otherLoginLable.mas_centerY);
        make.right.equalTo(self.view).with.offset(0);
        make.left.equalTo(otherLoginLable.right).with.offset(0);
        make.height.mas_equalTo(@1);
    }];
    
    
    weChatButton = [UIButton new];
    [self.view addSubview:weChatButton];
    [weChatButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(otherLoginLable.mas_centerX);
        make.top.equalTo(otherLoginLable.bottom).with.offset(10);
        make.height.mas_equalTo(@90);
        make.width.mas_equalTo(@90);
    }];
    [weChatButton setImage:[UIImage imageNamed:@"weChat"] forState:UIControlStateNormal];
    [weChatButton addTarget:self action:@selector(ClickweChatButton) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark 点击获取验证码
-(void)ClickCodeButton{
    
    if (self.teleponeField.text.length < 1) {
        [self.teleponeField becomeFirstResponder];
        return;
    }
    [NetworkManager requestGetVerifyCodeWithAction:@"login"
                                            mobile:self.teleponeField.text
                                           success:^(NSDictionary *dictResponse)
     {
         if ([dictResponse[@"err"] intValue] == 0)
         {
             [self startTime];
             [SVProgressHUD showSuccessWithStatus:dictResponse[@"msg"]];
             
         }
         else
         {
             [SVProgressHUD showErrorWithStatus:dictResponse[@"msg"]];
         }
         self.bIsNewOne = [dictResponse[@"state"] boolValue];
     } failure:^(NSError *error) {
     }];
}

#pragma mark 点击登录按钮
-(void)ClickconfirmButton{
    
    if (self.teleponeField.text.length < 1) {
        [self.teleponeField becomeFirstResponder];
        return;
    }
    if (self.codeField.text.length < 1) {
        [self.codeField becomeFirstResponder];
        return;
    }
//    NSLog(@"device.devicetoke = %@",theAppdelegate.deviceToken);
    
    [SVProgressHUD showWithStatus:@"登录中..."];
    [NetworkManager requestVerifyCodeWithCode:self.codeField.text mobile:self.teleponeField.text device_token:theAppdelegate.deviceToken success:^(NSDictionary *dictResponse) {
        ProgressDismiss;

        if (![dictResponse[@"err"] intValue] == 0)
        {
            [SVProgressHUD showSuccessWithStatus:dictResponse[@"msg"]];
         
        }
        else
        {
             [SVProgressHUD showSuccessWithStatus:dictResponse[@"msg"]];
            //保存各种信息
            
            NSDictionary *dict = (NSDictionary *)dictResponse[@"content"];
            [UserModel setMid:[dict objectForKey:@"id"]];
            [UserModel setMobile:[dict objectForKey:@"mobile"]];
            [UserModel setPassword:[dict objectForKey:@"password"]];
            
            [self dismissViewControllerAnimated:YES completion:^{
            }];
        }
    } failure:^(NSError *error) {
        ProgressDismiss;
    }];
}

#pragma mark 点击微信登录按钮
-(void)ClickweChatButton{

    
    __block ZCLoginVC *weekself = self;
    [WeichatManager getUserInfo:^(DZWeichatUserInfoModel *userInfoModel) {

        NSLog(@"微信unionid = %@ ,openid = %@",userInfoModel.unionid,userInfoModel.openid);
        [SVProgressHUD showWithStatus:@"登录中..."];
        [NetworkManager requestGetMemberInfobyunionidWithUnionid:userInfoModel.unionid openid:userInfoModel.openid from_type:@"2" device_token:theAppdelegate.deviceToken success:^(NSDictionary *dictResponse) {
            ProgressDismiss;
            //保存各种信息
            [UserModel setMid:[dictResponse objectForKey:@"id"]];
            [UserModel setMobile:[dictResponse objectForKey:@"mobile"]];
            [UserModel setPassword:[dictResponse objectForKey:@"password"]];
            [UserModel setUsername:[dictResponse objectForKey:@"username"]];
            NSLog(@"name = %@",[dictResponse objectForKey:@"username"]);
            
            [weekself dismissViewControllerAnimated:YES completion:^{
            }];
        } failure:^(NSError *error) {
            ProgressDismiss;
        }];
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.teleponeField resignFirstResponder];
    [self.codeField resignFirstResponder];
}

-(void)startTime{
    __block int timeout=59 ; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                codeButton.userInteractionEnabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [codeButton setTitle:[NSString stringWithFormat:@"等待%@秒",strTime] forState:UIControlStateNormal];
                codeButton.userInteractionEnabled = NO;
                
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
    
}


@end
